package com.xnx3.wangmarket.admin.controller;

import com.xnx3.StringUtil;
import com.xnx3.j2ee.func.AttachmentFile;
import com.xnx3.j2ee.service.SqlService;
import com.xnx3.j2ee.util.Page;
import com.xnx3.j2ee.util.Sql;
import com.xnx3.j2ee.vo.BaseVO;
import com.xnx3.j2ee.vo.UploadFileVO;
import com.xnx3.wangmarket.admin.Func;
import com.xnx3.wangmarket.admin.cache.GenerateHTML;
import com.xnx3.wangmarket.admin.cache.Template;
import com.xnx3.wangmarket.admin.cache.pc.IndexAboutUs;
import com.xnx3.wangmarket.admin.cache.pc.IndexNews;
import com.xnx3.wangmarket.admin.entity.*;
import com.xnx3.wangmarket.admin.service.*;
import com.xnx3.wangmarket.admin.util.AliyunLog;
import com.xnx3.wangmarket.admin.vo.SiteColumnTreeVO;
import com.xnx3.wangmarket.admin.vo.TemplatePageListVO;
import com.xnx3.wangmarket.admin.vo.TemplatePageVO;

import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping({"/column"})
public class ColumnController extends BaseController {

    @Resource
    private SqlService sqlService;

    @Resource
    private SiteService siteService;

    @Resource
    private NewsService newsService;

    @Resource
    private SiteColumnService siteColumnService;

    @Resource
    private TemplateService templateService;

    @Resource
    private InputModelService inputModelService;

    @Resource
    private CompanyInfoService companyInfoService;

    @Resource
    ColumnTypeService columnTypeService;

    @RequestMapping({"/list${url.suffix}"})
    public String list(HttpServletRequest request, Model model) {
        Sql sql = new Sql(request);
        sql.setSearchTable("site_column");

        sql.setSearchColumn(new String[0]);
        sql.appendWhere("userid = " + getUserId());

        int count = this.sqlService.count("site_column", sql.getWhere());

        Page page = new Page(count, 15, request);

        sql.setSelectFromAndPage("SELECT * FROM site_column", page);

        sql.setDefaultOrderBy("site_column.rank ASC");

        List list = this.sqlService.findBySql(sql, SiteColumn.class);

        AliyunLog.addActionLog(getSiteId(), "查看栏目列表");

        model.addAttribute("list", list);

        model.addAttribute("page", page);
        model.addAttribute("siteid", Integer.valueOf(getSiteId()));
        model.addAttribute("AttachmentFileUrl", AttachmentFile.netUrl());
        return "column/list";
    }

    @RequestMapping({"/popupList${url.suffix}"})
    public String popupList(HttpServletRequest request, Model model) {
        Sql sql = new Sql(request);
        sql.setSearchTable("site_column");

        sql.setSearchColumn(new String[0]);
        sql.appendWhere("siteid = " + getSiteId() + " AND userid = " + getUserId());

        int count = this.sqlService.count("site_column", sql.getWhere());

        Page page = new Page(count, 200, request);

        sql.setSelectFromAndPage("SELECT * FROM site_column", page);

        sql.setDefaultOrderBy("site_column.rank ASC");

        List list = this.sqlService.findBySql(sql, SiteColumn.class);

        AliyunLog.addActionLog(getSiteId(), "针对PC端通用模版模式下，查看栏目列表");

        model.addAttribute("list", list);

        model.addAttribute("page", page);
        model.addAttribute("siteid", Integer.valueOf(getSiteId()));
        model.addAttribute("site", getSite());
        model.addAttribute("cursorStyle", (getSite().getTemplateName() != null) && (getSite().getTemplateName().length() > 0) ? "" : "cursor: all-scroll;");
        model.addAttribute("AttachmentFileUrl", AttachmentFile.netUrl());
        return "column/popup_list";
    }

    @RequestMapping({"/popupListForTemplate${url.suffix}"})
    public String popupListForTemplate(HttpServletRequest request, Model model) {
        List list = this.siteColumnService.getSiteColumnTreeVOByCache();

        AliyunLog.addActionLog(getSiteId(), "CMS模式下，获取网站下的栏目列表");

        model.addAttribute("list", list);

        model.addAttribute("site", getSite());
        return "column/popupListForTemplate";
    }

    @RequestMapping({"/column${url.suffix}"})
    public String column(HttpServletRequest request, @RequestParam(value = "id", required = false, defaultValue = "0") int id, Model model) {
        com.xnx3.wangmarket.admin.entity.Site site = getSite();
        String title = "";
        SiteColumn siteColumn = null;
        String iconImage = "";
        if (id > 0) {
            siteColumn = (SiteColumn) this.sqlService.findById(SiteColumn.class, id);
            if (siteColumn == null) {
                return error(model, "要修改的栏目导航不存在！");
            }
            if (siteColumn.getSiteid().intValue() - site.getId().intValue() != 0)
                return error(model, "栏目不属于您，无法修改！");
        } else {
            siteColumn = new SiteColumn();
            siteColumn.setType(SiteColumn.TYPE_PAGE);
            siteColumn.setUsed(SiteColumn.USED_ENABLE);
        }
        model.addAttribute("siteColumn", siteColumn);
        model.addAttribute("site", site);

        if (id > 0) {
            String icon = siteColumn.getIcon().indexOf("://") == -1 ? AttachmentFile.netUrl() + "site/" + site.getId() + "/column_icon/" + siteColumn.getIcon() : siteColumn.getIcon();
            iconImage = "<img src=\"" + icon + "\" height=\"30\" onclick=\"window.open('" + icon + "');\" alt=\"当前的图标\" style=\"cursor:pointer;\">";
        }
        model.addAttribute("iconImage", iconImage);

        AliyunLog.addActionLog(getSiteId(), "进入添加、编辑导航栏目页面");

        this.siteService.getTemplateCommonHtml(site, title, model);
        return "column/column";
    }

    @RequestMapping({"/popupColumnUpdate${url.suffix}"})
    public String popupColumnUpdate(HttpServletRequest request, @RequestParam(value = "id", required = false, defaultValue = "0") int id, Model model) {
        com.xnx3.wangmarket.admin.entity.Site site = getSite();
        SiteColumn siteColumn = (SiteColumn) this.sqlService.findById(SiteColumn.class, id);
        if (siteColumn == null) {
            return error(model, "要修改的栏目导航不存在！");
        }
        if (siteColumn.getUserid().intValue() - getUserId() != 0) {
            return error(model, "栏目不属于你，无法修改");
        }

        String icon = siteColumn.getIcon().indexOf("://") == -1 ? AttachmentFile.netUrl() + "site/" + site.getId() + "/column_icon/" + siteColumn.getIcon() : siteColumn.getIcon();

        AliyunLog.addActionLog(getSiteId(), "通用电脑网站模式下，弹出更该栏目名字的弹出框");

        model.addAttribute("icon", icon);
        model.addAttribute("siteColumn", siteColumn);
        return "column/popup_column";
    }

    @RequestMapping({"/popupColumnGaoJiUpdate${url.suffix}"})
    public String popupColumnGaoJiUpdate(HttpServletRequest request, @RequestParam(value = "id", required = false, defaultValue = "0") int id, Model model) {
        com.xnx3.wangmarket.admin.entity.Site site = getSite();
        SiteColumn siteColumn;
        if (id > 0) {
            siteColumn = (SiteColumn) this.sqlService.findById(SiteColumn.class, id);
            if (siteColumn == null) {
                return error(model, "要修改的栏目导航不存在！");
            }
            if (siteColumn.getUserid().intValue() - getUserId() != 0)
                return error(model, "栏目不属于你，无法修改");
        } else {
            siteColumn = new SiteColumn();
        }

        String icon = siteColumn.getIcon().indexOf("://") == -1 ? AttachmentFile.netUrl() + "site/" + site.getId() + "/column_icon/" + siteColumn.getIcon() : siteColumn.getIcon();

        AliyunLog.addActionLog(getSiteId(), "通用电脑网站模式下，打开更该栏目属性的页面");

        model.addAttribute("icon", icon);
        model.addAttribute("siteColumn", siteColumn);
        model.addAttribute("site", getSite());
        return "column/popup_columnGaoJi";
    }

    @RequestMapping({"/popupColumnForTemplate${url.suffix}"})
    public String popupColumnForTemplate(HttpServletRequest request, Model model, @RequestParam(value = "id", required = false, defaultValue = "0") int id, @RequestParam(value = "isCopy", required = false, defaultValue = "0") int isCopy) {
        com.xnx3.wangmarket.admin.entity.Site site = getSite();
        List<ColumnType> columnTypes = columnTypeService.getColumnTypeListByCache();
        SiteColumn siteColumn;
        if (id > 0) {
            siteColumn = (SiteColumn) this.sqlService.findById(SiteColumn.class, id);
            if (siteColumn == null) {
                return error(model, "要修改的栏目导航不存在！");
            }
            if (siteColumn.getUserid().intValue() - getUserId() != 0) {
                return error(model, "栏目不属于你，无法修改");
            }

            if (isCopy == 1) {
                try {
                    SiteColumn sc = siteColumn.clone();
                    siteColumn = null;
                    siteColumn = sc;
                    siteColumn.setId(null);
                    if (siteColumn.getCodeName() != null) {
                        siteColumn.setCodeName(siteColumn.getCodeName() + "1");
                    }
                    siteColumn.setName("复制" + siteColumn.getName());
                } catch (CloneNotSupportedException e) {
                    e.printStackTrace();
                }
            }
        } else {
            siteColumn = new SiteColumn();
            siteColumn.setType(SiteColumn.TYPE_NEWS);
            siteColumn.setParentid(Integer.valueOf(0));
        }

        TemplatePageListVO templatePageListVO = this.templateService.getTemplatePageListByCache(request);

        StringBuffer tpl_view_option = new StringBuffer();
        for (int i = 0; i < templatePageListVO.getList().size(); i++) {
            TemplatePage tp = ((TemplatePageVO) templatePageListVO.getList().get(i)).getTemplatePage();
            if ((tp.getType().shortValue() - TemplatePage.TYPE_NEWS_VIEW.shortValue() == 0) || (tp.getType().shortValue() - TemplatePage.TYPE_ALONEPAGE.shortValue() == 0)) {
                if ((siteColumn.getTemplatePageViewName() != null) && (siteColumn.getTemplatePageViewName().equals(tp.getName())))
                    tpl_view_option.append("<option value=\"" + tp.getName() + "\" selected=\"selected\">"  + tp.getRemark() + "</option>");
                else {
                    tpl_view_option.append("<option value=\"" + tp.getName() + "\">"+ tp.getRemark() + "</option>");
                }
            }
        }
        if (tpl_view_option.length() == 0) {
            for (ColumnType columnType : columnTypes) {
                if (columnType.getType()-ColumnType.TYPE_NEWS_VIEW==0 || columnType.getType()-ColumnType.TYPE_ALONEPAGE==0) {
                    if ((siteColumn.getTemplatePageViewName() != null) && (!siteColumn.getTemplatePageViewName().equals(columnType.getName()))) {
                        tpl_view_option.append("<option value=" + columnType.getName() + " selected=\"selected\">" + columnType.getRemarket() + "</option>");
                    }else{
                        tpl_view_option.append("<option value=\"" + columnType.getName() + "\">" + columnType.getRemarket() + "</option>");
                    }
                }
            }
        }

        model.addAttribute("tpl_view_option", tpl_view_option.toString());

        StringBuffer tpl_list_option = new StringBuffer();
        for (int i = 0; i < templatePageListVO.getList().size(); i++) {
            TemplatePage tp = ((TemplatePageVO) templatePageListVO.getList().get(i)).getTemplatePage();
            if (tp.getType().shortValue() - TemplatePage.TYPE_NEWS_LIST.shortValue() == 0) {
                if ((siteColumn.getTemplatePageListName() != null) && (siteColumn.getTemplatePageListName().equals(tp.getName())))
                    tpl_list_option.append("<option value=\"" + tp.getName() + "\" selected=\"selected\">" + tp.getRemark() + "</option>");
                else {
                    tpl_list_option.append("<option value=\"" + tp.getName() + "\">"+ tp.getRemark() + "</option>");
                }
            }
        }
        if (tpl_list_option.length() == 0) {
            for (ColumnType ct:columnTypes) {
                if(ct.getType()-ColumnType.TYPE_NEWS_LIST==0){
                    if ((siteColumn.getTemplatePageListName() != null) && (!siteColumn.getTemplatePageListName().equals(ct.getName()))){
                        tpl_list_option.append("<option value=\"" + ct.getName() + "\" selected=\"selected\">" + ct.getRemarket() + "</option>");
                    } else {
                        tpl_list_option.append("<option value=\"" + ct.getName() + "\">" + ct.getRemarket() + "</option>");
                    }
                }
            }
//            tpl_list_option.append("<option value=\"\" selected=\"selected\">暂无可选的列表模版</option>");
        }
        model.addAttribute("tpl_list_option", tpl_list_option.toString());

        List siteColumnTreeList = this.siteColumnService.getSiteColumnTreeVOByCache();
        StringBuffer parentColumn = new StringBuffer();
        if (((siteColumn.getParentid() != null) && (siteColumn.getParentid().intValue() > 0)) || ((siteColumn.getParentCodeName() != null) && (siteColumn.getParentCodeName().length() > 0))) {
            parentColumn.append("<option value=\"\">顶级栏目</option>");
        } else parentColumn.append("<option value=\"\" \" selected=\"selected\">顶级栏目</option>");

        for (int i = 0; i < siteColumnTreeList.size(); i++) {
            SiteColumn sc = ((SiteColumnTreeVO) siteColumnTreeList.get(i)).getSiteColumn();

            if ((siteColumn.getId() == null) || (sc.getId().intValue() - siteColumn.getId().intValue() != 0)) {
                if ((sc.getCodeName() != null) && (siteColumn.getParentCodeName() != null) && (siteColumn.getParentCodeName().equals(sc.getCodeName())))
                    parentColumn.append("<option value=\"" + sc.getCodeName() + "\" selected=\"selected\">" + sc.getName() + "</option>");
                else {
                    parentColumn.append("<option value=\"" + sc.getCodeName() + "\">" + sc.getName() + "</option>");
                }

            }

        }

        List inputModelList = this.inputModelService.getInputModelListForSession();

        String inputModelOptions = "";

        String imCodeName = null;
        if ((siteColumn.getInputModelCodeName() != null) && (siteColumn.getInputModelCodeName().length() > 0)) {
            imCodeName = siteColumn.getInputModelCodeName();
        }

        boolean findDefaultModel = false;
        for (int i = 0; i < inputModelList.size(); i++) {
            InputModel inputModel = (InputModel) inputModelList.get(i);
            if ((imCodeName != null) && (inputModel.getCodeName().equals(imCodeName))) {
                findDefaultModel = true;
                inputModelOptions = inputModelOptions + "<option value=\"" + inputModel.getCodeName() + "\" selected=\"selected\">" + inputModel.getCodeName() + "," + inputModel.getRemark() + "</option>";
            } else {
                inputModelOptions = inputModelOptions + "<option value=\"" + inputModel.getCodeName() + "\">" + inputModel.getCodeName() + "," + inputModel.getRemark() + "</option>";
            }
        }

        if (!findDefaultModel)
            inputModelOptions = "<option value=\"0\" selected=\"selected\">系统内置模型</option>" + inputModelOptions;
        else {
            inputModelOptions = "<option value=\"0\">系统内置模型</option>" + inputModelOptions;
        }

        AliyunLog.addActionLog(getSiteId(), "CMS模式下，添加、修改栏目");

        model.addAttribute("parentColumnOption", parentColumn.toString());
        model.addAttribute("site", site);
        model.addAttribute("siteColumn", siteColumn);
        model.addAttribute("inputModelOptions", inputModelOptions);
        return "column/popupColumnForTemplate";
    }

    @RequestMapping(value = {"/popupColumnUpdateSubmit${url.suffix}"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST})
    @ResponseBody
    public BaseVO popupColumnUpdateSubmit(HttpServletRequest request, SiteColumn sc) {
        SiteColumn siteColumn = (SiteColumn) this.sqlService.findById(SiteColumn.class, sc.getId().intValue());
        if (siteColumn == null) {
            return error("栏目不存在");
        }
        if (siteColumn.getUserid().intValue() - getUserId() != 0) {
            return error("栏目不属于你，无法修改");
        }
        com.xnx3.wangmarket.admin.entity.Site site = getSite();
        boolean updateName = !sc.getName().equals(siteColumn.getName());

        siteColumn.setName(filter(sc.getName()));
        this.sqlService.save(siteColumn);

        AliyunLog.addActionLog(siteColumn.getId().intValue(), "保存栏目：" + siteColumn.getName());

        if (siteColumn.getType() == SiteColumn.TYPE_PAGE) {
            this.siteColumnService.createNonePage(siteColumn, site, updateName);
        }

        if ((siteColumn.getType() == SiteColumn.TYPE_NEWS) || (siteColumn.getType() == SiteColumn.TYPE_IMAGENEWS)) {
            this.newsService.generateListHtml(site, siteColumn);
        }

        List list = this.sqlService.findBySqlQuery("SELECT * FROM site_column WHERE siteid = " + site.getId() + " AND used = " + SiteColumn.USED_ENABLE + " ORDER BY rank ASC", SiteColumn.class);
        new com.xnx3.wangmarket.admin.cache.Site().siteColumn(list, site);

        if (updateName) {
            GenerateHTML gh = new GenerateHTML(site);
            String indexHtml = gh.getGeneratePcIndexHtml();
            if (Template.isAnnoConfigById_Have(indexHtml, siteColumn.getId().intValue())) {
                if (siteColumn.getType().shortValue() - SiteColumn.TYPE_PAGE.shortValue() == 0) {
                    if (site.getAboutUsCid().intValue() - siteColumn.getId().intValue() == 0) {
                        News news = (News) this.sqlService.findAloneBySqlQuery("SELECT * FROM news WHERE cid = " + siteColumn.getId(), News.class);
                        NewsData newsData = (NewsData) this.sqlService.findById(NewsData.class, news.getId().intValue());
                        IndexAboutUs.refreshIndexData(site, siteColumn, news, newsData.getText());
                    }
                } else if ((siteColumn.getType().shortValue() - SiteColumn.TYPE_IMAGENEWS.shortValue() == 0) || (siteColumn.getType().shortValue() - SiteColumn.TYPE_NEWS.shortValue() == 0)) {
                    List newsList = this.sqlService.findBySqlQuery("SELECT * FROM news WHERE cid = " + siteColumn.getId() + " AND status = " + News.STATUS_NORMAL + " ORDER BY id DESC LIMIT 0,10", News.class);
                    IndexNews.refreshIndexData(site, siteColumn, newsList);
                }
            }
        }

        return success();
    }

    @RequestMapping(value = {"savePopupColumnGaoJiUpdate${url.suffix}"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST})
    @ResponseBody
    public BaseVO savePopupColumnGaoJiUpdate(SiteColumn siteColumn, HttpServletRequest request, Model model) {
        BaseVO vo = new BaseVO();
        com.xnx3.wangmarket.admin.entity.Site site = getSite();
        if (site == null) {
            vo.setBaseVO(0, "要修改的导航栏目所属的站点不存在！");
            return vo;
        }
        if (site.getUserid().intValue() != getUserId()) {
            vo.setBaseVO(0, "站点不属于您，无法修改！");
            return vo;
        }

        String name = filter(StringUtil.filterHtmlTag(siteColumn.getName()));
        if ((name == null) || (name.length() < 1)) {
            vo.setBaseVO(0, "您要创建的导航栏目叫什么名字呢");
            return vo;
        }

        boolean addColumn = true;
        boolean updateName = false;
        SiteColumn sc = new SiteColumn();
        String oldCodeName = null;
        if ((siteColumn.getId() != null) && (siteColumn.getId().intValue() > 0)) {
            addColumn = false;
            sc = (SiteColumn) this.sqlService.findById(SiteColumn.class, siteColumn.getId().intValue());
            if (sc.getSiteid().intValue() - site.getId().intValue() != 0) {
                vo.setBaseVO(0, "要修改的栏目不属于您，无权修改");
                return vo;
            }
            if (!sc.getName().equals(name)) {
                updateName = true;
            }
            oldCodeName = sc.getCodeName();
        } else {
            sc.setUserid(Integer.valueOf(getUserId()));
            sc.setSiteid(site.getId());
            sc.setRank(Integer.valueOf(0));
        }

        sc.setName(name);

        sc.setUrl(filter(siteColumn.getUrl()));
        sc.setUsed(Short.valueOf(siteColumn.getUsed() == null ? 1 : siteColumn.getUsed().shortValue()));
        sc.setType(siteColumn.getType());
        sc.setTemplatePageListName(filter(siteColumn.getTemplatePageListName()));
        sc.setTemplatePageViewName(filter(siteColumn.getTemplatePageViewName()));
        sc.setListNum(Integer.valueOf(siteColumn.getListNum() == null ? 10 : siteColumn.getListNum().intValue()));
        sc.setEditMode(siteColumn.getEditMode() == null ? SiteColumn.EDIT_MODE_INPUT_MODEL : siteColumn.getEditMode());
        sc.setDownColumn(siteColumn.getDownColumn());

        String inputModelCodeName = StringUtil.filterHtmlTag(siteColumn.getInputModelCodeName());
        if ((inputModelCodeName == null) || (inputModelCodeName.length() == 0) || (inputModelCodeName.equals("0"))) {
            sc.setInputModelCodeName(null);
        } else {
            boolean isExist = false;

            List inputModelList = this.inputModelService.getInputModelListForSession();
            for (int i = 0; i < inputModelList.size(); i++) {
                InputModel im = (InputModel) inputModelList.get(i);
                if (im.getCodeName().equals(inputModelCodeName)) {
                    isExist = true;
                    break;
                }
            }

            if (!isExist) {
                return error("您选择的该栏目的输入模型不存在！请重试。");
            }
            sc.setInputModelCodeName(inputModelCodeName);
        }

        if (Func.isCMS(site)) {
            if (((sc.getParentCodeName() == null) && (siteColumn.getParentCodeName() != null)) || (!sc.getParentCodeName().equals(siteColumn.getParentCodeName()))) {
                if (siteColumn.getParentCodeName().length() == 0) {
                    sc.setParentCodeName("");
                    sc.setParentid(Integer.valueOf(0));
                } else {
                    SiteColumn s = (SiteColumn) this.sqlService.findAloneBySqlQuery("SELECT * FROM site_column WHERE siteid=" + site.getId() + " AND code_name ='" + Sql.filter(siteColumn.getParentCodeName()) + "'", SiteColumn.class);
                    if (s == null) {
                        vo.setBaseVO(0, "您填写的父栏目代码没有找到指定的栏目，请检查您是否有栏目代码为" + siteColumn.getParentCodeName() + "的栏目");
                        return vo;
                    }

                    if ((!addColumn) && (this.sqlService.count("site_column", "WHERE parentid = " + siteColumn.getId()) > 0)) {
                        return error("目前系统暂时只支持一级子栏目，当前此栏目已经有下级栏目了，无法再作为子栏目");
                    }

                    sc.setParentCodeName(filter(siteColumn.getParentCodeName()));
                    sc.setParentid(s.getId());
                }

            }

            if (((sc.getCodeName() == null) && (siteColumn.getCodeName() != null)) || ((sc.getCodeName() != null) && (siteColumn.getCodeName() == null)) || (!sc.getCodeName().equals(siteColumn.getCodeName()))) {
                if (siteColumn.getCodeName().length() == 0) {
                    sc.setCodeName("");
                } else {
                    sc.setCodeName(filter(siteColumn.getCodeName()));

                    List sclistCache = this.siteColumnService.getSiteColumnListByCache();
                    for (int i = 0; i < sclistCache.size(); i++) {
                        SiteColumn s = (SiteColumn) sclistCache.get(i);
                        if ((s.getCodeName().equals(sc.getCodeName())) && (
                                (sc.getId() == null) || (sc.getId().intValue() - s.getId().intValue() != 0))) {
                            vo.setBaseVO(0, "您当前的栏目代码已经有栏目使用了，请换一个吧，网站内栏目代码是唯一的");
                            return vo;
                        }
                    }
                }
            }
        } else {
            sc.setParentid(Integer.valueOf(0));
        }

        String oldIconName = sc.getIcon();

        UploadFileVO upload = AttachmentFile.uploadImage("site/" + site.getId() + "/column_icon/", request, "iconFile", 100);
        if (upload.getResult() == 1) {
            sc.setIcon(upload.getFileName());
        }

        this.sqlService.save(sc);
        if (sc.getId().intValue() > 0) {
            if (sc.getType() == SiteColumn.TYPE_PAGE) {
                if (sc.getEditMode().shortValue() - SiteColumn.EDIT_MODE_TEMPLATE.shortValue() != 0) {
                    this.siteColumnService.createNonePage(sc, site, updateName);
                }
            }

            if (Func.isCMS(site)) {
                if ((oldCodeName != null) && (!sc.getCodeName().equals(oldCodeName))) {
                    this.sqlService.executeSql("UPDATE site_column SET parent_code_name = '" + Sql.filter(sc.getCodeName()) + "' WHERE parentid = " + sc.getId());
                }

                this.siteColumnService.updateSiteColumnByCache(sc);
            } else {
                if ((sc.getType() == SiteColumn.TYPE_NEWS) || (sc.getType() == SiteColumn.TYPE_IMAGENEWS)) {
                    this.newsService.generateListHtml(site, sc);
                }

                if (addColumn) {
                    new com.xnx3.wangmarket.admin.cache.Site().siteColumnRankAppend(site, sc.getId().intValue());
                }

                String siteColumnId = this.siteService.getSiteColumnId(sc, site);
                if (siteColumnId != null) {
                    site.setColumnId(siteColumnId);
                    this.sqlService.save(site);
                }

                List list = this.sqlService.findBySqlQuery("SELECT * FROM site_column WHERE siteid = " + site.getId() + " AND used = " + SiteColumn.USED_ENABLE + " ORDER BY rank ASC", SiteColumn.class);
                new com.xnx3.wangmarket.admin.cache.Site().siteColumn(list, site);

                if (sc.getName().equals(siteColumn.getName())) {
                    Template template = new Template(site);
                    GenerateHTML gh = new GenerateHTML(site);
                    String indexHtml = gh.getGeneratePcIndexHtml();
                    if (Template.isAnnoConfigById_Have(indexHtml, sc.getId().intValue())) {
                        if (sc.getType().shortValue() - SiteColumn.TYPE_PAGE.shortValue() == 0) {
                            if (site.getAboutUsCid().intValue() - sc.getId().intValue() == 0) {
                                News news = (News) this.sqlService.findAloneBySqlQuery("SELECT * FROM news WHERE cid = " + sc.getId(), News.class);
                                NewsData newsData = (NewsData) this.sqlService.findById(NewsData.class, news.getId().intValue());
                                IndexAboutUs.refreshIndexData(site, sc, news, newsData.getText());
                            }
                        } else if ((sc.getType().shortValue() - SiteColumn.TYPE_IMAGENEWS.shortValue() == 0) || (sc.getType().shortValue() - SiteColumn.TYPE_NEWS.shortValue() == 0)) {
                            List newsList = this.sqlService.findBySqlQuery("SELECT * FROM news WHERE cid = " + sc.getId() + " AND status = " + News.STATUS_NORMAL + " ORDER BY id DESC LIMIT 0,10", News.class);
                            IndexNews.refreshIndexData(site, sc, newsList);
                        }
                    }
                }

            }

            if ((oldIconName != null) && (oldIconName.length() != 0) &&
                    (oldIconName.indexOf("/") == -1)) {
                AttachmentFile.deleteObject("site/" + site.getId() + "/column_icon/" + oldIconName);
            }

            if (addColumn)
                AliyunLog.addActionLog(sc.getId().intValue(), "添加栏目：" + sc.getName());
            else {
                AliyunLog.addActionLog(sc.getId().intValue(), "修改栏目：" + sc.getName());
            }

            return vo;
        }
        vo.setBaseVO(0, "保存失败");
        return vo;
    }

    @RequestMapping(value = {"updateRank${url.suffix}"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST})
    @ResponseBody
    public BaseVO updateRank(HttpServletRequest request, @RequestParam(value = "id", required = false, defaultValue = "0") int id, @RequestParam(value = "rank", required = false, defaultValue = "0") int rank) {
        if (id < 1) {
            return error("请传入要操作的栏目编号");
        }
        SiteColumn siteColumn = (SiteColumn) this.sqlService.findById(SiteColumn.class, id);
        if (siteColumn == null) {
            return error("要操作的栏目不存在");
        }
        if (siteColumn.getSiteid().intValue() - getSiteId() != 0) {
            return error("栏目不属于您，无法操作");
        }

        siteColumn.setRank(Integer.valueOf(rank));
        this.sqlService.save(siteColumn);

        this.siteColumnService.updateSiteColumnByCache(siteColumn);

        AliyunLog.insert(request, siteColumn.getId().intValue(), "更改栏目排序");

        return success();
    }

    @RequestMapping(value = {"saveColumn${url.suffix}"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST})
    @ResponseBody
    public BaseVO saveColumn(SiteColumn siteColumn, HttpServletRequest request, Model model) {
        com.xnx3.wangmarket.admin.entity.Site site = getSite();

        String name = filter(siteColumn.getName());
        if ((name == null) || (name.length() < 1)) {
            return error("您要创建的导航栏目叫什么名字呢");
        }

        boolean addSite = true;
        boolean updateName = false;
        SiteColumn sc = null;
        if ((siteColumn.getId() != null) && (siteColumn.getId().intValue() > 0)) {
            addSite = false;
            sc = (SiteColumn) this.sqlService.findById(SiteColumn.class, siteColumn.getId().intValue());

            if (sc.getSiteid().intValue() - site.getId().intValue() != 0) {
                AliyunLog.insert(request, sc.getId().intValue(), "warn", "修改的栏目不是自己的，要修改的栏目名为：" + sc.getName());
                return error("栏目不属于您，修改失败！您的操作系统已记录");
            }
            if (!sc.getName().equals(name))
                updateName = true;
        } else {
            sc = new SiteColumn();
            sc.setUserid(Integer.valueOf(getUserId()));
            sc.setSiteid(site.getId());
            if (site.getClient().shortValue() - com.xnx3.wangmarket.admin.entity.Site.CLIENT_CMS.shortValue() != 0) {
                sc.setParentid(Integer.valueOf(0));
            }
        }

        sc.setName(name);

        sc.setUrl(filter(siteColumn.getUrl()));
        sc.setUsed(siteColumn.getUsed());
        sc.setType(siteColumn.getType());

        String oldIconName = null;

        UploadFileVO upload = AttachmentFile.uploadImage("site/" + site.getId() + "/column_icon/", request, "iconFile", 100);
        if (upload.getResult() == 1) {
            oldIconName = sc.getIcon();
            sc.setIcon(upload.getFileName());
        }
        this.sqlService.save(sc);
        if (sc.getId().intValue() > 0) {
            if ((oldIconName != null) && (oldIconName.indexOf("/") == -1)) {
                AttachmentFile.deleteObject("site/" + site.getId() + "/column_icon/" + oldIconName);
            }

            if (addSite)
                AliyunLog.addActionLog(sc.getId().intValue(), "添加栏目：" + sc.getName());
            else {
                AliyunLog.addActionLog(sc.getId().intValue(), "修改栏目：" + sc.getName());
            }

            if (sc.getType().shortValue() - SiteColumn.TYPE_PAGE.shortValue() == 0) {
                this.siteColumnService.createNonePage(sc, site, updateName);
            }

            if (site.getClient().shortValue() - com.xnx3.wangmarket.admin.entity.Site.CLIENT_PC.shortValue() == 0) {
                com.xnx3.wangmarket.admin.entity.Site s = (com.xnx3.wangmarket.admin.entity.Site) this.sqlService.findById(com.xnx3.wangmarket.admin.entity.Site.class, site.getId().intValue());
                String siteColumnId = this.siteService.getSiteColumnId(sc, s);
                if (siteColumnId != null) {
                    s.setColumnId(siteColumnId);
                    this.sqlService.save(s);
                }

            }

            if (site.getClient().shortValue() - com.xnx3.wangmarket.admin.entity.Site.CLIENT_CMS.shortValue() != 0) {
                if ((sc.getType() == SiteColumn.TYPE_NEWS) || (sc.getType() == SiteColumn.TYPE_IMAGENEWS)) {
                    this.newsService.generateListHtml(site, sc);
                }

                List list = this.sqlService.findBySqlQuery("SELECT * FROM site_column WHERE siteid = " + site.getId() + " AND used = " + SiteColumn.USED_ENABLE + " ORDER BY rank ASC", SiteColumn.class);
                new com.xnx3.wangmarket.admin.cache.Site().siteColumn(list, site);

                if (addSite) {
                    new com.xnx3.wangmarket.admin.cache.Site().siteColumnRankAppend(site, sc.getId().intValue());
                }

                if (site.getClient().shortValue() - com.xnx3.wangmarket.admin.entity.Site.CLIENT_PC.shortValue() == 0) {
                    if (sc.getName().equals(siteColumn.getName())) {
                        GenerateHTML gh = new GenerateHTML(site);
                        String indexHtml = gh.getGeneratePcIndexHtml();
                        if (Template.isAnnoConfigById_Have(indexHtml, sc.getId().intValue())) {
                            if (sc.getType().shortValue() - SiteColumn.TYPE_PAGE.shortValue() == 0) {
                                if (site.getAboutUsCid().intValue() - sc.getId().intValue() == 0) {
                                    News news = (News) this.sqlService.findAloneBySqlQuery("SELECT * FROM news WHERE cid = " + sc.getId(), News.class);
                                    NewsData newsData = (NewsData) this.sqlService.findById(NewsData.class, news.getId().intValue());
                                    IndexAboutUs.refreshIndexData(site, sc, news, newsData.getText());
                                }
                            } else if ((sc.getType().shortValue() - SiteColumn.TYPE_IMAGENEWS.shortValue() == 0) || (sc.getType().shortValue() - SiteColumn.TYPE_NEWS.shortValue() == 0)) {
                                List newsList = this.sqlService.findBySqlQuery("SELECT * FROM news WHERE cid = " + sc.getId() + " AND status = " + News.STATUS_NORMAL + " ORDER BY id DESC LIMIT 0,10", News.class);
                                IndexNews.refreshIndexData(site, sc, newsList);
                            }
                        }
                    }
                }

            }

            return success();
        }
        return error("保存失败！");
    }

    @RequestMapping(value = {"/saveRank${url.suffix}"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST})
    @ResponseBody
    public BaseVO saveRank(HttpServletRequest request, @RequestParam(value = "rankString", required = false, defaultValue = "") String rankString) {
        BaseVO baseVO = new BaseVO();
        com.xnx3.wangmarket.admin.entity.Site site = getSite();
        if (site == null) {
            baseVO.setBaseVO(0, "要修改的栏目导航所属的网站不存在！");
            return baseVO;
        }
        if (site.getUserid().intValue() != getUserId()) {
            baseVO.setBaseVO(0, "站点不属于您，无法修改！");
            return baseVO;
        }

        AliyunLog.addActionLog(site.getId().intValue(), "保存栏目排序");

        new com.xnx3.wangmarket.admin.cache.Site().siteColumnRank(site, Sql.filter(rankString));
        return new BaseVO();
    }

    @RequestMapping({"/resetRank${url.suffix}"})
    public String resetRank(HttpServletRequest request, @RequestParam(value = "siteid", required = false, defaultValue = "0") int siteid, Model model) {
        if (siteid == 0) {
            return error(model, "请传入站点编号");
        }
        com.xnx3.wangmarket.admin.entity.Site site = (com.xnx3.wangmarket.admin.entity.Site) this.sqlService.findById(com.xnx3.wangmarket.admin.entity.Site.class, siteid);
        if (site == null) {
            return error(model, "要重置栏目导航顺序的网站不存在！");
        }
        if (site.getUserid().intValue() != getUserId()) {
            return error(model, "站点不属于您，无法修改！");
        }

        this.siteColumnService.resetColumnRankAndJs(site);

        AliyunLog.addActionLog(site.getId().intValue(), "重置栏目排序");

        return success(model, "重置栏目排序成功", Func.getConsoleRedirectUrl());
    }

    @RequestMapping({"delete${url.suffix}"})
    @ResponseBody
    public BaseVO delete(@RequestParam(value = "id", required = false, defaultValue = "0") int id) {
        SiteColumn siteColumn = (SiteColumn) this.sqlService.findById(SiteColumn.class, id);
        if (siteColumn == null) {
            return error("要删除的栏目不存在！");
        }
        if (siteColumn.getUserid().intValue() - getUserId() != 0) {
            return error("栏目不属于你，无法删除");
        }

        this.sqlService.delete(siteColumn);

        if (Func.isCMS(getSite())) {
            this.siteColumnService.deleteSiteColumnByCache(siteColumn.getId().intValue());
        }

        AliyunLog.addActionLog(siteColumn.getId().intValue(), "删除栏目：" + siteColumn.getName());

        return success();
    }
}